﻿using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;

namespace Library.Util
{
    public class LdapUtil
    {
        public bool Login(string domainName, string username, string password)
        {
            try
            {
                using (var directoryEntry = new DirectoryEntry("LDAP://" + domainName, username, password))
                {
                    return !directoryEntry.NativeObject.Equals(null);
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                BasePersistence.Log.Error("LDAP Sorgulama Hatası-COM Exception", ex);
                return false;
            }
            catch (Exception ex)
            {
                BasePersistence.Log.Error("LDAP Sorgulama Hatası", ex);
                throw;
            }
        }

        public List<string> SearchDirectory(string domainName, string filter)
        {
            try
            {
                var entry = new DirectoryEntry("LDAP://" + domainName);
                var searcher = new DirectorySearcher(entry) {Filter = filter};
                return (from SearchResult sr in searcher.FindAll() select sr.GetDirectoryEntry().Name).ToList();
            }
            catch (Exception ex)
            {
                BasePersistence.Log.Error("LDAP Sorgulama Hatası", ex);
                throw;
            }
        }

        public List<string> Computers(string domainName)
        {
            return SearchDirectory(domainName, "(objectClass=computer)");
        }

        public List<string> Persons(string domainName)
        {
            return SearchDirectory(domainName, "(objectClass=person)");
        }
    }
}